package crowx.android.AndCellTrack;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;

import com.google.android.maps.MapActivity;

abstract class AndCellTrackBase extends MapActivity {
	protected static final String TAG = "AndCellTrack";
	
	protected abstract void onStateChanged(CellInfo cellInfo);
	
	@Override
	protected void onResume() {
		super.onResume();
		android.util.Log.v(TAG, "AndCellTrack.onResume");
		bindService();		
	}
    
    @Override
	protected void onPause() {
		super.onPause();
		android.util.Log.v(TAG, "AndCellTrack.onPause");
		unbindService();
	}
	
    private void bindService() {
		android.util.Log.d(TAG, "AndCellTrack.bindService");
		bindService(new Intent(getApplicationContext(), AndCellTrackService.class), mConnection, Context.BIND_AUTO_CREATE);
	}
	
	private void unbindService() {
		android.util.Log.d(TAG, "AndCellTrack.unbindService");
		unbindService(mConnection);
	}
    
	private final ICellTrackStateObserver.Stub cellTrackStateListener = new ICellTrackStateObserver.Stub() {
		@Override
		public void onStateChanged(CellInfo cellInfo) throws RemoteException {
			AndCellTrackBase.this.onStateChanged(cellInfo);
		}
	};
	
	private final ServiceConnection mConnection = new ServiceConnection() {		
		private IAndCellTrackServiceBase andCellTrackService = null;
		
		public void onServiceConnected(ComponentName className, IBinder service) {
        	android.util.Log.d(TAG, "AndCellTrack.ServiceConnection.onServiceConnected");
        	andCellTrackService = IAndCellTrackServiceBase.Stub.asInterface((IBinder)service);
            try {
				andCellTrackService.registerObserver(cellTrackStateListener);
				onStateChanged(andCellTrackService.getCellInfo());
			} catch (RemoteException e) {
				android.util.Log.e(TAG, "AndCellTrack.ServiceConnection.onServiceConnected", e);
			}
        }
        
        public void onServiceDisconnected(ComponentName className) {
        	android.util.Log.d(TAG, "AndCellTrack.ServiceConnection.onServiceDisconnected");
            try {
				andCellTrackService.unregisterObserver(cellTrackStateListener);
			} catch (RemoteException e) {
				android.util.Log.e(TAG, "AndCellTrack.ServiceConnection.onServiceDisconnected", e);
			}
            andCellTrackService = null;
        }
    };
}
